package com.apes.fn.pi.basicInfo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.server.servicePlan.repository.ServicePlanRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.esb.processor.connector.http.HttpTransporter;
import com.apes.framework.util.MapUtil;
import com.apes.framework.util.NetUtil;
import com.apes.framework.util.PropertiesUtils;
import com.apes.framework.util.statistics.Statistics;
import com.apes.framework.util.statistics.StatisticsRepository;
import com.apes.pi.model.Timestamp;
import com.apes.pi.repository.TimestampRepository;
import com.apes.pi.service.PiManager;
import com.apes.scm.masterdata.frame.model.Store;
import com.apes.scm.masterdata.frame.repository.StoreRepository;
import org.apache.http.client.config.RequestConfig;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by lishikun on 2020/9/9 16:04
 */
@Service("basicInfoService")
public class BasicInfoService extends DomainService {

    @Autowired
    private EntityManager em;

    // 汽车维修电子健康档案系统
    private static String carRepairTokenUrl = "https://tsb.xlbzone.com/restservices/lcipprodatarest/lcipprogetaccesstoken/query";
    private static String carRepairUpDataUrl = "https://tsb.xlbzone.com/restservices/lcipprodatarest/lcipprocarfixrecordadd/query";


    // 广州市机动车维修行业综合管理信息平台
    @Value("${caam.token_url}")
    private String token_url;
    @Value("${caam.updata_url}")
    private String updata_url;
    @Autowired
    StatisticsRepository repository;

    @Autowired
    TimestampRepository timestampRepository;

    private String assess_token = "";

    /**
     * 上传汽车维修电子健康档案系统数据
     * @param request
     */
    private List<Map<String, String>> upDataCarRepair(SimpleRequest request) {
        List<CaamDeptAccount> deptAccounts = getDeptMessage();
        //获取时间戳
        String interfaceId = "ipBasicInfoService.upDataCarRepair";
        Timestamp timestamp = timestampRepository.findOne(interfaceId);
        String newTimestamp;
        //判断是否存在时间戳
        if ( timestamp == null) {
            //新建时间戳
            Timestamp t = new Timestamp();
            t.setId(interfaceId);
            t.setType("timestamp");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            newTimestamp = simpleDateFormat.format(new Date().getTime());
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.DAY_OF_MONTH, -1);
            t.setTime(newTimestamp);
            t.setLastUpdatedStamp(c.getTime());
            timestampRepository.save(t);
            timestamp = t;
        } else {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            //获取当前时间
            newTimestamp = simpleDateFormat.format(new Date().getTime());
        }
        List<Map<String, String>> list = new ArrayList<>();
        for (CaamDeptAccount deptAccount : deptAccounts) {
            Map<String, String> map = MapUtil.mapped(deptAccount);
            map.put("newTimestamp", newTimestamp);
            map.put("lastUpdatedStamp", timestamp.getTime());
            map.put("deptId", deptAccount.getDept().getId());
            list.add(map);
        }
        timestamp.setTime(newTimestamp);
        timestampRepository.saveAndFlush(timestamp);
//        for (Map<String, String> map : list) {
//            SimpleRequest simpleRequest = new SimpleRequest();
//            simpleRequest.setData(map);
//            this.caamhrUpData(simpleRequest);
//        }
        return list;
    }

    // 广州市机动车维修行业综合管理信息平台
    public void caamUpData(SimpleRequest request) {
        Map map = request.getMap();
        JSONObject createMap = new JSONObject();
        createMap.put("companycode", map.get("caamApiNumber").toString());
        createMap.put("companypassword", map.get("caamApiPassword").toString());
        String a = createMap.toString();
        Map obj = new HashMap();
        obj.put("data", a);
        String token = JSONObject.parseObject(interfaceData(token_url, obj)).getString("access_token");
        List data = getCarRepair(map);
        caamUpData(token, data);
    }

    public void caamhrUpData(SimpleRequest request) {
        Map map = request.getMap();
        String caamhrApiNumber = map.get("caamhrApiNumber").toString();
        String caamhrApiPassword = map.get("caamhrApiPassword").toString();
        String token = getToken(carRepairTokenUrl, caamhrApiNumber, caamhrApiPassword);
        List data = getCarRepair(map);
        upDataCarRepair(token, data, map, carRepairUpDataUrl);
    }

    private void upDataCarRepair(String token, List data, Map store, String url) {
        Map map = (Map)data.stream().collect(Collectors.groupingBy(json -> {
            return ((Map)json).get("COSTLISTCODE").toString();
        }));
        Set set = map.keySet();
        for (Object o : set) {
            Map allData = new HashMap();
            Map basicinfoData = (Map)((List)map.get(o)).get(0);
            Map basicinfo = new HashMap();

            basicinfo.put("vehicleplatenumber", basicinfoData.get("VEHICLEPLATENUMBER"));
            basicinfo.put("companyname", basicinfoData.get("COMPANYNUM"));
            basicinfo.put("vin", basicinfoData.get("VIN"));
            basicinfo.put("repairdate", basicinfoData.get("REPAIRDATE"));
            basicinfo.put("repairmileage", basicinfoData.get("REPAIRMILEAGE"));
            basicinfo.put("settledate", basicinfoData.get("SETTLEDATE"));
            basicinfo.put("faultdescription", basicinfoData.get("FAULTDESCRIPTION"));
            basicinfo.put("costlistcode", basicinfoData.get("COSTLISTCODE"));
            // 过滤工时的商品
            List vehiclepartslist = (List)((List)map.get(o)).stream().filter(i-> {
                return !"工时".equals(((Map)i).get("CATEGORYNAME").toString());
            }).map(vehiclepart ->{
                return MapUtil.mapper("partscode", ((Map)vehiclepart).get("PARTSCODE"), "partsquantity", ((Map)vehiclepart).get("PARTSQUANTITY"),
                        "partsname", ((Map)vehiclepart).get("PARTSNAME"));
            }).collect(Collectors.toList());
            // 获取工时的商品
            List a = ((List)((List)map.get(o)).stream().filter(i-> {
                return "工时".equals(((Map)i).get("CATEGORYNAME").toString());
            }).collect(Collectors.toList()));
            List repairprojectlist = (List)a.stream().map(vehiclepart ->{
                return MapUtil.mapper("repairproject", ((Map)vehiclepart).get("REPAIRPROJECT"), "workinghours", ((Map)vehiclepart).get("WORKINGHOURS"));
            }).collect(Collectors.toList());
            allData.put("access_token", token);
            allData.put("basicInfo", basicinfo);
            allData.put("vehiclepartslist", vehiclepartslist);
            allData.put("repairprojectlist", repairprojectlist);
            String result = newInterfaceData(url, allData);
            JSONObject log = new JSONObject();
            log.put("request", allData);
            log.put("response",result);
            log.put("method", url);
            writerLogging(log);
        }
    }


    private void caamUpData(String token, List data) {
        Map map = (Map)data.stream().collect(Collectors.groupingBy(json -> {
            return ((Map)json).get("COSTLISTCODE").toString();
        }));

        Set set = map.keySet();
        for (Object o : set) {
            Map basicinfoData = (Map)((List)map.get(o)).get(0);
            Map basicinfo = new HashMap();
            JSONObject allData = new JSONObject();

            basicinfo.put("vehicleplatenumber", basicinfoData.get("VEHICLEPLATENUMBER"));
            basicinfo.put("companyname", basicinfoData.get("COMPANYNUM"));
            basicinfo.put("vin", basicinfoData.get("VIN"));
            basicinfo.put("repairdate", basicinfoData.get("REPAIRDATE"));
            basicinfo.put("repairmileage", basicinfoData.get("REPAIRMILEAGE"));
            basicinfo.put("settledate", basicinfoData.get("SETTLEDATE"));
            basicinfo.put("faultdescription", basicinfoData.get("FAULTDESCRIPTION"));
            basicinfo.put("costlistcode", basicinfoData.get("COSTLISTCODE"));
            // 过滤工时的商品
            List vehiclepartslist = (List)((List)map.get(o)).stream().filter(i-> {
                return !"工时".equals(((Map)i).get("CATEGORYNAME").toString());
            }).map(vehiclepart ->{
                return MapUtil.mapper("partscode", ((Map)vehiclepart).get("PARTSCODE"), "partsquantity", ((Map)vehiclepart).get("PARTSQUANTITY"),
                        "partsname", ((Map)vehiclepart).get("PARTSNAME"));
            }).collect(Collectors.toList());
            // 获取工时的商品
            List a = ((List)((List)map.get(o)).stream().filter(i-> {
                 return "工时".equals(((Map)i).get("CATEGORYNAME").toString());
            }).collect(Collectors.toList()));
            List repairprojectlist = (List)a.stream().map(vehiclepart ->{
                return MapUtil.mapper("repairproject", ((Map)vehiclepart).get("REPAIRPROJECT"), "workinghours", ((Map)vehiclepart).get("WORKINGHOURS"));
            }).collect(Collectors.toList());

            allData.put("access_token", token);
            allData.put("basicinfo", basicinfo);
            allData.put("vehiclepartslist", vehiclepartslist);
            allData.put("repairprojectlist", repairprojectlist);
            Map param = MapUtil.mapper("data", allData);
            String result = interfaceData(updata_url, param);
            System.out.println(result);
            JSONObject resultJson = JSONObject.parseObject(result);
            JSONObject log = new JSONObject();
            log.put("request", allData);
            log.put("response",resultJson);
            log.put("method", updata_url);
            writerLogging(log);
        }
    }

    private List getCarRepair(Map map) {
        return getNewCarRepair(map);
    }

    private String getToken(String url, String companycode, String companypassword) {

        JSONObject createMap = new JSONObject();
        createMap.put("companycode", companycode);
        createMap.put("companypassword", companypassword);
        String ret = interfaceData(url, createMap);
        JSONObject resultJson = JSONObject.parseObject(ret);
        JSONObject log = new JSONObject();
        log.put("request", createMap);
        log.put("response",resultJson);
        log.put("method", url);
        writerLogging(log);
        return resultJson.getString("access_token");
    }

    /**
     * 获取门店信息
     * @return
     */
    private List<CaamDeptAccount> getDeptMessage() {
        List<CaamDeptAccount> deptAccounts = SpringManager.getBean(CaamDeptAccountRepository.class).findAllByCaamhrApiNumberIsNotNull();
        return deptAccounts;
    }

    public String interfaceData(String url, Map<String, Object> param) {
        Map headers = new HashMap();
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        HttpTransporter transporter = new HttpTransporter();
        transporter.setUrl(url);
        transporter.setHeaders(headers);
        SimpleRequest rqst = new SimpleRequest();
        rqst.setData(param);
        return (String) transporter.process(rqst);
    }

    public String newInterfaceData(String url, Map<String, Object> param) {
        Map headers = new HashMap();
        headers.put("Content-Type", "application/json");
        HttpTransporter transporter = new HttpTransporter();
        transporter.setUrl(url);
        transporter.setHeaders(headers);
        SimpleRequest rqst = new SimpleRequest();
        rqst.setData(JSONObject.toJSONString(param));

        return (String) transporter.process(rqst);
    }


    private RequestConfig getRequestConfig(int socketTimeout, int connectTimeout) {
        return RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
    }


    public List upBasicInfo(SimpleRequest request) {
        //获取时间戳
        String interfaceId = "ipBasicInfoService.BasicInfo";
        Timestamp timestamp = timestampRepository.findOne(interfaceId);
        String newTimestamp;
        JSONArray jsonArray;
        //判断是否存在时间戳
        if ( timestamp == null) {
            //新建时间戳
            Timestamp t = new Timestamp();
            t.setId(interfaceId);
            t.setType("timestamp");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            newTimestamp = simpleDateFormat.format(new Date().getTime());
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.DAY_OF_MONTH,-1);
            t.setTime(newTimestamp);
            t.setLastUpdatedStamp(c.getTime());
            timestampRepository.save(t);
        } else {

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            //获取当前时间
            newTimestamp = simpleDateFormat.format(new Date().getTime());
        }
        List<CaamDeptAccount> deptAccounts = SpringManager.getBean(CaamDeptAccountRepository.class).findAllByCaamApiNumberIsNotNull();
        List<Map<String, String>> list = new ArrayList<>();
        for (CaamDeptAccount deptAccount : deptAccounts) {
            Map<String, String> map = MapUtil.mapped(deptAccount);
            map.put("newTimestamp", newTimestamp);
            map.put("lastUpdatedStamp", timestamp.getTime());
            map.put("deptId", deptAccount.getDept().getId());
            list.add(map);
        }
        timestamp.setTime(newTimestamp);
        timestampRepository.saveAndFlush(timestamp);
//        for (Map<String, String> map : list) {
//            SimpleRequest simpleRequest = new SimpleRequest();
//            simpleRequest.setData(map);
//            this.caamUpData(simpleRequest);
//        }
        return list;

    }
    /**
     * 获取老系统维修数据
     *
     * @param
     * @param
     * @return
     */
    public JSONArray getOldBasicInfo(String newTimestamp, String lastUpdatedStamp) {
        //获取所有维修基本数据
        List<Map> allBasicInfo = getAllBasicInfo(newTimestamp, lastUpdatedStamp);
        JSONArray jsonArray = new JSONArray();
        if (allBasicInfo.size() > 0) {
            for (int i = 0; i < allBasicInfo.size(); i++) {
                JSONObject allDate = new JSONObject();
                //获取维修配件列表和维修项目列表数据
                List<Map> list = getVehiclepartsList(allBasicInfo.get(i).get("COSTLISTCODE").toString());
                if (list.size() == 0)
                    continue;
                List<Map> vehiclepartsList = new ArrayList<Map>();
                List<Map> repairprojectList = new ArrayList<Map>();
                //数据进行拆分成两个数组
                for (int j = 0; j < list.size(); j++) {
                    Map map1 = new HashMap();
                    map1.put("PARTSNAME", list.get(j).get("PARTSNAME"));
                    map1.put("PARTSCODE", list.get(j).get("PARTSCODE"));
                    map1.put("PARTSQUANTITY", list.get(j).get("PARTSQUANTITY"));
                    vehiclepartsList.add(map1);
                    Map map2 = new HashMap();
                    map2.put("REPAIRPROJECT", list.get(j).get("REPAIRPROJECT"));
                    map2.put("WORKINGHOURS", list.get(j).get("WORKINGHOURS"));
                    repairprojectList.add(map2);
                }
                //获取token
                //根据门店的账号和密码获取汽车协会的token
                String costlistcode  = (String)allBasicInfo.get(i).get("COMPANYCODE");
                String companypassword = (String)allBasicInfo.get(i).get("COMPANYPASSWORD");
                String urlStr = token_url;
                JSONObject createMap = new JSONObject();
                createMap.put("companycode", costlistcode);
                createMap.put("companypassword", companypassword);
                String a = createMap.toString();
                Map obj = new HashMap();
                obj.put("data", a);
                try {
                    String ret = interfaceData(urlStr, obj);
//                    String ret = URLConnectionUtil.doPost(urlStr, obj);
                    JSONObject resultJson = JSONObject.parseObject(ret);
                    assess_token = resultJson.getString("access_token");
                    JSONObject log = new JSONObject();
                    log.put("request", createMap);
                    log.put("response",resultJson);
                    log.put("method", token_url);
                    writerLogging(log);
                } catch (Exception e){
                    throw new RuntimeException("调用汽车协会接口报错："+ e.getMessage());
                }
                //封装数据
                allDate.put("access_token", assess_token);
                allDate.put("basicinfo", allBasicInfo.get(i));
                allDate.put("vehiclepartslist", vehiclepartsList);
                allDate.put("repairprojectlist", repairprojectList);
                jsonArray.add(allDate);
            }
        }
        return jsonArray;
    }


    protected List<Map> find(String sql, Map<String, Object> params) {
        Query query = em.createNativeQuery(sql);
        // Query 接口是 spring-data-jpa 的接口，而 SQLQuery 接口是 hibenate 的接口，这里的做法就是先转成 hibenate 的查询接口对象，然后设置结果转换器
        query.getParameters().stream().forEach(param -> {
            query.setParameter(param.getName(), params.get(param.getName()));
        });
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }

    //老：获取服务单的维修基本信息
    public List<Map> getAllBasicInfo(String newTimestamp, String lastUpdatedStamp) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("select a.cphm as vehicleplatenumber, '' as vehicleplatecolor, \n" +
                "                       (select z.cjhm from CPH z where z.clnm = a.clnm) vin, \n" +
                "                       (select GSSH from mas_gsxx z where z.gsid = a.gsid and rownum = 1) companynum, \n" +
                "                       a.shrq_sj as repairdate, \n" +
                "                       a.lcbds as repairmileage, a.fwgzxx as faultdescription, \n" +
                "                       a.hzrq_sj as settledate, a.fwdh as costlistcode ,b.wgptzh as companycode, b.wgptmi as companypassword\n" +
                "                  from ser_fwd a ,MAS_MDXX b\n" +
                "                 where a.hzrq_sj is not null \n" +
                "                   and a.hzrq_sj >= " +"to_date(:lastTimestamp, 'yyyy-mm-dd hh24:mi:ss')" +
                "                   and a.hzrq_sj < " + "to_date(:newTimestamp, 'yyyy-mm-dd hh24:mi:ss')"  +
                "                   and a.zdrq_sj >= sysdate - 30\n" +
                "                   and a.fwmdid = b.mdid " +
                "                   and b.wgptzh is not null" +
                "                   and b.wgptmi is not null");
        JSONObject param = new JSONObject();
        param.put("lastTimestamp", lastUpdatedStamp);
        param.put("newTimestamp", newTimestamp);
        List<Map> allBasicInfo = find(stringBuffer.toString(), param);
        for (int i = 0; i < allBasicInfo.size(); i++) {
            allBasicInfo.set(i, nullToEmpty(allBasicInfo.get(i)));
            if (allBasicInfo.get(i).get("FAULTDESCRIPTION").equals("")) {
                allBasicInfo.get(i).put("FAULTDESCRIPTION", "车辆维修");
            }
            DateFormat df1 = new SimpleDateFormat("yyyyMMdd");
            if("".equals(allBasicInfo.get(i).get("SETTLEDATE").toString())){
                allBasicInfo.get(i).put("SETTLEDATE", df1.format(new Date()));
            }

            else {
                allBasicInfo.get(i).put("SETTLEDATE", df1.format((Date)allBasicInfo.get(i).get("SETTLEDATE")));
            }
            if("".equals(allBasicInfo.get(i).get("REPAIRDATE").toString())){
                allBasicInfo.get(i).put("REPAIRDATE", df1.format(new Date()));
            }
            else {
                allBasicInfo.get(i).put("REPAIRDATE", df1.format((Date)allBasicInfo.get(i).get("REPAIRDATE")));
            }


        }
        return allBasicInfo;
    }

    /**
     * 根据服务单号获取所有的维修商品
     *
     * @param id
     * @return
     */
    public List<Map> getVehiclepartsList(String id) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("select b.spid partscode, b.spmc partsname, " +
                "        b.xssl partsquantity, b.Fwlxmc repairproject, (select z.sgsc " +
                "            from mas_spxx_fwgs z " +
                "           where z.spid = b.spid " +
                "             and rownum = 1) workinghours " +
                "   from ser_fwdfa a, ser_fwdfasp b " +
                "  where a.fwfah = b.fwfah " +
                "  and b.Fwlxmc != '洗车' " +
                "  and b.Fwlxmc != '美容' " +
                "  and b.ZJJG=1   " +
                "  and a.fwdh = " + id);
        JSONObject parm = new JSONObject();
        List<Map> list = find(stringBuffer.toString(), parm);
        for (int i = 0; i < list.size(); i++) {
            list.set(i, nullToEmpty(list.get(i)));
        }
        return list;
    }

    //老：获取服务单的维修基本信息
    public List<Map> getNewCarRepair(Map map) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("SELECT T.ID COSTLISTCODE, (SELECT CAR_LICENSE  " +
                "           FROM FN_CUSTOMER_EXPAND A " +
                "          WHERE A.ID = T.FN_CUSTOMER_EXPAND_ID) VEHICLEPLATENUMBER, " +
                "       (SELECT VIN " +
                "           FROM FN_CUSTOMER_EXPAND A " +
                "          WHERE A.ID = T.FN_CUSTOMER_EXPAND_ID) VIN, '' AS VEHICLEPLATECOLOR, " +
                "          (SELECT MAX(MILEAGE)  NUM FROM FN_PICK_UP_CAR A  " +
                "          WHERE A.LICENSE_NUMBER = T.CAR_LISCENCE) REPAIRMILEAGE , " +
                "       (SELECT A.NAME FROM MAS_PARTY A, MAS_PARTY_ROLE B " +
                "           WHERE A.ID = B.PARTY_ID AND B.ID = T.COMPANY_ID) COMPANYNUM,  " +
                "           CASE WHEN T.RECEIVABLE_DATE IS NULL THEN TO_CHAR(SYSDATE, 'yyyyMMdd')  " +
                "              ELSE TO_CHAR(T.RECEIVABLE_DATE,'yyyyMMdd') END   SETTLEDATE, " +
                "           TO_CHAR(T.CREATE_DATE, 'yyyyMMdd') AS REPAIRDATE,  " +
                "          (CASE WHEN T.FAULT_DESCRIPTION IS NULL THEN '车辆维修' ELSE T.FAULT_DESCRIPTION END) FAULTDESCRIPTION , " +
                "           B.PRODUCT_ID AS PARTSCODE, (SELECT NAME FROM MAS_PRODUCT A WHERE A.ID = B.PRODUCT_ID) PARTSNAME, " +
                "           (B.SALE_QTY - B.QTY_END) PARTSQUANTITY, " +
                "           (SELECT NAME FROM MAS_SERVE_TYPE A WHERE A.ID= B.SERVE_TYPE_ID) REPAIRPROJECT, " +
                "           (SELECT CASE WHEN MAX(SERVICE_HOURS) IS NULL THEN 0 ELSE MAX(SERVICE_HOURS) END FROM  MAS_PRODUCT_SERVICE_HOURS A WHERE B.PRODUCT_ID = A.PRODUCT_ID AND A.VALID = 1) WORKINGHOURS," +
                "           (SELECT A.NAME FROM MAS_CATEGORY A, MAS_PRODUCT E WHERE A.ID = E.CATEGORY_ID AND E.ID = B.PRODUCT_ID)CATEGORYNAME  " +
                "  FROM SER_SERVICE_PLAN T, SER_SERVICE_PLAN_ITEM B  " +
                "  WHERE T.CREATE_DATE > SYSDATE - 30 " +
                "  AND T.ID = B.SERVICE_PLAN_ID " +
                "  AND T.STATE = 'receivables' " +
                "  AND T.RECEIVABLE_DATE IS NOT NULL " +
                "  AND  B.SERVE_TYPE_ID <> '002'  " +
                "  AND B.SERVE_TYPE_ID <> '001'   " +
//                "  AND B.QUALITY_TEST_DATE IS NOT NULL " +
////                "  AND T.RECEIVABLE_DATE >= " +"TO_DATE(:lastTimestamp, 'yyyy-mm-dd hh24:mi:ss')" +
////                "  AND T.RECEIVABLE_DATE < " + "TO_DATE(:newTimestamp, 'yyyy-mm-dd hh24:mi:ss')"  +
////                "  AND T.SERVICE_DEPT_ID = :dpetId" +
                "  AND B.SALE_QTY - B.QTY_END > 0 " +
                "  AND B.SALE_QTY - B.QTY_END > 0 " +
                "  AND EXISTS (SELECT 1 FROM MAS_SERVE_TYPE A WHERE A.ID = B.SERVE_TYPE_ID AND A.NAME != '洗车' AND A.NAME != '美容') " );
        JSONObject param = new JSONObject();
        param.put("lastTimestamp", map.get("lastUpdatedStamp").toString());
        param.put("newTimestamp", map.get("newTimestamp").toString());
        param.put("deptId", map.get("deptId").toString());
        List<Map> allBasicInfo = find(stringBuffer.toString(), param);
        return allBasicInfo;
    }



    //处理空值转空字符串
    public Map<String, String> nullToEmpty(Map<String, String> map) {
        Set<String> set = map.keySet();
        if (set != null && !set.isEmpty()) {
            for (String key : set) {
                if (map.get(key) == null) {
                    map.put(key, "");
                }
            }
        }
        return map;
    }

    //写入日志
    public void writerLogging(JSONObject json) {
        Statistics statistics = new Statistics();
        statistics.setServer(NetUtil.getServerIp());
        statistics.setBeginTime(LocalDateTime.now().toString());
        statistics.setRequest(json.getString("request"));
        statistics.setResponse(json.getString("response"));
        statistics.setMethod(json.getString("method"));
        statistics.setInvokeMethod("pi.BasicInfo.query");
        repository.save(statistics);
    }


}
